package paper.parse;

import java.util.Vector;
import java.util.Iterator;

public class Author implements Comparable {
    String surname;
    Vector<String> givenNames = new Vector<String>();
    double prob;
    Vector<Double> sequenceProb = new Vector<Double>();

    public Author() {
    }

    public void addSurname(String s) {
        if (surname == null) {
            surname = s.toUpperCase();
        } else {
            surname += " " + s.toUpperCase();
        }
    }

    public void addGivenName(String s) {
        givenNames.add(s.toUpperCase());
    }
    
    public boolean equals(Author x) {
        if (!surname.equals(x.surname)) {
            return false;
        }
        if (givenNames.size() != x.givenNames.size()) {
            return false;
        }
        for (int s = 0; s < givenNames.size(); s++) {
            if (!givenNames.get(s).equals(x.givenNames.get(s))) {
                return false;
            }
        }
        return true;
    }
    
    public boolean isPrefixOf(Author x) {
        if (!surname.equals(x.surname)) {
            return false;
        }
        if (givenNames.size() > x.givenNames.size()) {
            return false;
        }
        for (int s = 0; s < givenNames.size(); s++) {
            if (!x.givenNames.get(s).startsWith(givenNames.get(s))) {
                return false;
            }
        }
        return true;
    }

    public void addProbability(double p) {
        prob += p;
    }
    
    public void addSequence(int s, double p) {
        if (sequenceProb.size() <= s) {
            sequenceProb.setSize(s+1);
        }
        Double t = sequenceProb.get(s);
        if (t == null) {
            t = p;
        } else {
            t = t + p;
        }
        sequenceProb.set(s, t);
    }
    
    public void addWholeSequence(Author x) {
        if (sequenceProb.size() < x.sequenceProb.size()) {
            sequenceProb.setSize(x.sequenceProb.size());
        }
        for (int s = 0; s < sequenceProb.size() && s < x.sequenceProb.size(); s++) {
            Double p = x.sequenceProb.get(s);
            Double t = sequenceProb.get(s);
            if (p != null) {
                if (t == null) {
                    t = p;
                } else {
                    t = t + p;
                }
            }
            sequenceProb.set(s, t);
        }
    }

    public int compareTo(Object xx) {
        Author x = (Author) xx;
        if (x.prob < prob) {
            return -1;
        }
        if (x.prob > prob) {
            return 1;
        }
        return 0;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(surname.charAt(0));
        sb.append(surname.substring(1).toLowerCase());
        sb.append(" ");
        for (Iterator<String> j = givenNames.iterator(); j.hasNext();) {
            String firstName = j.next();
            sb.append(firstName.charAt(0));
        }
        return sb.toString();
    }
}
